package com.utopia.keyvalue.store.index;

import java.io.File;
import java.io.IOException;

import junit.framework.TestCase;

import org.apache.commons.lang.RandomStringUtils;

import com.utopia.keyvalue.store.impl.disk.FileStore;

/**
 * @author yanjiaqiang
 * @date 2011-3-17
 * @version $Id: FileStoreTest.java 5 2011-03-22 09:23:42Z JiaqiangYan@gmail.com $
 */
public class FileStoreTest extends TestCase {

	public void testNewFileStore() throws IOException {
		File file = File.createTempFile("index", "test");
		file.delete();

		int filesize = 1024 * 1024 * 10;
		FileStore store = new FileStore(file, filesize);

		assertEquals(store.getFileSize(), filesize);
		assertEquals(store.getRecordSize(), 0);
		assertEquals(store.getWriteOffset(), 12);

		store.close();
		file.delete();
	}

	public void testExsitFileStore() throws IOException {
		File file = File.createTempFile("index", "test");
		file.delete();
		int filesize = 1024 * 1024 * 10;
		FileStore store = new FileStore(file, filesize);
		store.put("123456789".getBytes());
		store.close();

		FileStore newstore = new FileStore(file, filesize);
		assertEquals(newstore.getFileSize(), filesize);
		assertEquals(newstore.getRecordSize(), 1);
		assertEquals(newstore.getWriteOffset(), 12 + 9);

		newstore.close();
		file.delete();

	}

	public void testAll() throws IOException {
		File file = File.createTempFile("index", "test");
		file.delete();
		int filesize = 1024 * 1024 * 10;
		String data = "123456789";
		FileStore store = new FileStore(file, filesize);
		store.put(data.getBytes());

		assertEquals(store.getFileSize(), filesize);
		assertEquals(store.getRecordSize(), 1);
		assertEquals(store.getWriteOffset(), 12 + data.length());

		assertEquals(new String(store.get(store.getStartOffset(), data.length())), data);

		store.close();
		file.deleteOnExit();
	}

	public void testIncrementFilesize() throws IOException {
		File file = File.createTempFile("index", "test");
		file.delete();
		int filesize = 1024 * 1024;
		FileStore store = new FileStore(file, filesize);
		store.put(RandomStringUtils.randomAlphanumeric(2 * 1024 * 1024).getBytes());

		assertEquals(store.getFileSize(), 4 * 1024 * 1024);
		assertEquals(store.getRecordSize(), 1);
		assertEquals(store.getWriteOffset(), 12 + 2 * 1024 * 1024);

		store.close();
		file.deleteOnExit();
	}
}
